# views.py : 路由 + 视图函数
from http.client import responses
from urllib import request, response

from flask import Blueprint,render_template,request,redirect,jsonify
from .models import *
import random
from .exts import mail
from flask_mail import Message

#蓝图
blue = Blueprint('user',__name__)

from functools import wraps
# 装饰器：登陆验证
def login_required(fn):
    @wraps(fn)
    def inner(*args, **kwargs):
        # 获取cookie，得到登录的用户
        user_id = request.cookies.get('user_id', None)
        if user_id:
            user = Username.query.get(user_id)
            request.user = user
            return fn(*args, **kwargs)
        else:
            # 如果没有登录，则跳转到登陆页面
            return redirect('/login/')
    return inner

@blue.route('/')
@blue.route('/<int:pages>')
@blue.route('/index/')
@blue.route('/index/<int:pages>')
def index(pages=1):
    user_id = request.cookies.get('user_id', None)
    user = Username.query.get(user_id)
    page = int(request.args.get('page',pages))
    per_page = int(request.args.get('per_page',10))
    p = User.query.paginate(page=page,per_page=per_page,error_out=False)
    return render_template('index.html',p=p,user=user)

@blue.route('/login/',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        select = request.form.get('admin')
        if select == 'user':
            user = Username.query.filter_by(username=username,password=password).first()
            if user:
                response = redirect('/user/')
                response.set_cookie('user_id', str(user.user_id), max_age=3600 * 24 * 7)
                return response
            else:
                return '用户名或密码错误'
        elif select == 'admin':
            admin = Admin.query.filter_by(admin=username,password=password).first()
            if admin:
                response = redirect('/admin/')
                response.set_cookie('admin_id', str(admin.id), max_age=3600 * 24 * 7)
                return response
            else:
                return '用户名或密码错误'
    return render_template('login.html')

def generate_verification_code():
    return str(random.randint(1000,9999))
verification_codes = {}
@blue.route('/register/',methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    elif request.method == 'POST':
        if 'submit1' in request.form:
            username = request.form.get('username')
            password = request.form.get('password')
            cfpassword = request.form.get('cfpassword')
            email = request.form.get('email')
            code = generate_verification_code()
            verification_codes[email] = code
            print(verification_codes)
            # 发送邮件
            try:
                msg = Message(
                    subject='您的验证码',  # 邮件标题
                    sender='2603614545@qq.com',  # 发件人（需与配置一致）
                    recipients=[email]  # 收件人
                )
                msg.body = f'您的验证码是：{code}，5分钟内有效。'  # 邮件正文
                mail.send(msg)
                return render_template('register.html',username=username,password=password,cfpassword=cfpassword,email=email)
            except Exception as e:
                return jsonify({'success': False, 'error': str(e)}), 500
        elif 'submit2' in request.form:
            username = request.form.get('username')
            user_id = User.query.filter_by(name=username).first().id
            password = request.form.get('password')
            cfpassword = request.form.get('cfpassword')
            email = request.form.get('email')
            code = request.form.get('code')

            if password == cfpassword and code == verification_codes.get(email):
                try:
                    username = Username(user_id=user_id,username=username, password=password, email=email)
                    db.session.add(username)
                    db.session.commit()
                    return render_template('login.html')
                except Exception as e:
                    return f'error:{e}'
            elif password != cfpassword:
                return '密码不一致'
            elif code != verification_codes.get(email):

                return '验证码错误'
    return render_template('register.html')

@blue.route('/user/')
@login_required
def user():
    user = request.user
    user_id = request.cookies.get('user_id', None)
    users = User.query.get(int(user_id))
    email = Username.query.get(int(user_id)).email
    return render_template('user_home/user.html',username=user.username,users=users,email=email)

@blue.route('/wages/')
@login_required
def wages():
    user = request.user
    user_id = request.cookies.get('user_id', None)
    users = User.query.get(int(user_id))
    return render_template('user_home/wages.html',username=user.username,users=users)

@blue.route('/user/logout/')
def user_logout():
    response = redirect('/index/')
    response.delete_cookie('user_id')
    return response

def admin_login_required(fn):
    @wraps(fn)
    def inner(*args, **kwargs):
        # 获取cookie，得到登录的用户
        admin_id = request.cookies.get('admin_id', None)
        if admin_id:
            admin = Admin.query.get(admin_id)
            request.admin = admin
            return fn(*args, **kwargs)
        else:
            # 如果没有登录，则跳转到登陆页面
            return redirect('/login/')
    return inner

@blue.route('/admin/', methods=['GET','POST'])
@blue.route('/admin/<int:pages>', methods=['GET','POST'])
@admin_login_required
def admin(pages=1):
    if request.method == 'GET':
        admin = request.admin
        departments = Department.query.all()
        page = int(request.args.get('page', pages))
        per_page = int(request.args.get('per_page', 9))
        p = User.query.paginate(page=page, per_page=per_page, error_out=False)
        return render_template('admin/admin.html',p=p,departments=departments,admin=admin.admin)
    elif request.method == 'POST':
        departments = Department.query.all()
        for department in departments:
            if f'{department.id}' in request.form:
                name = request.form.get(f'{department.name}')
                wages = request.form.get(f'{department.wages}')
                department = Department.query.get(department.id)
                try:
                    department.name = name
                    department.wages = wages
                    db.session.commit()
                    return redirect('/admin/')
                except Exception as e:
                    print('error:',e)
                    return redirect('/admin/')
            else:
                pass
        if 'add' in request.form:
            name = request.form.get('add_name')
            wages = request.form.get('add_wages')
            try:
                department = Department(name=name, wages=wages)
                db.session.add(department)
                db.session.commit()
                return redirect('/admin/')
            except Exception as e:
                print('error:',e)
                return redirect('/admin/')
    return render_template('admin/admin.html')

@blue.route('/admin_job/',methods=['GET','POST'])
@blue.route('/admin_job/<int:pages>',methods=['GET','POST'])
@admin_login_required
def admin_job(pages=1):
    if request.method == 'GET':
        admin = request.admin
        jobs = Job.query.all()
        page = int(request.args.get('page', pages))
        per_page = int(request.args.get('per_page', 9))
        p = User.query.paginate(page=page, per_page=per_page, error_out=False)
        return render_template('admin/admin_job.html',p=p,jobs=jobs,admin=admin.admin)
    elif request.method == 'POST':
        jobs = Job.query.all()
        for job in jobs:
            if f'{job.id}' in request.form:
                name = request.form.get(f'{job.name}')
                wages = request.form.get(f'{job.wages}')
                job = Job.query.get(job.id)
                try:
                    job.name = name
                    job.wages = wages
                    db.session.commit()
                    return redirect('/admin_job/')
                except Exception as e:
                    print('error:',e)
                    return redirect('/admin_job/')
            else:
                pass
        if 'add' in request.form:
            name = request.form.get('add_name')
            wages = request.form.get('add_wages')
            try:
                job = Job(name=name, wages=wages)
                db.session.add(job)
                db.session.commit()
                return redirect('/admin_job/')
            except Exception as e:
                print('error:',e)
                return redirect('/admin_job/')
    return render_template('admin/admin_job.html')

@blue.route('/admin_staff/',methods=['GET','POST'])
@blue.route('/admin_staff/<int:pages>',methods=['GET','POST'])
@admin_login_required
def admin_staff(pages=1):
    if request.method == 'GET':
        admin = request.admin
        users = User.query.all()
        page = int(request.args.get('page', pages))
        per_page = int(request.args.get('per_page', 9))
        p = User.query.paginate(page=page, per_page=per_page, error_out=False)
        return render_template('admin/admin_staff.html',p=p,admin=admin.admin,users=users)
    elif request.method == 'POST':
        users = User.query.all()
        for user in users:
            if f'submit_{user.id}' in request.form:
                user.name = request.form.get(f'name_{user.id}')
                user.gender = 1 if request.form.get(f'gender_{user.id}')=='男' else 0
                user.number = request.form.get(f'number_{user.id}')
                email = request.form.get(f'email_{user.id}')
                print(email)
                departments = Department.query.all()
                for department in departments:
                    if request.form.get(f'department_id_{user.id}') == department.name:
                        user.department_id = department.id
                jobs = Job.query.all()
                for job in jobs:
                    if request.form.get(f'job_id_{user.id}') == job.name:
                        user.job_id = job.id
                user.overtime = request.form.get(f'overtime_{user.id}')
                try:
                    if email:
                        username = Username.query.get(user.id)
                        username.email = email
                    else:
                        pass
                    db.session.commit()
                    return redirect('/admin_staff/')
                except Exception as e:
                    print('error:',e)
                    return redirect('/admin_staff/')
            else:
                pass
        if 'add' in request.form:
            name = request.form.get('add_name')
            gender =1 if request.form.get('add_gender') == '男' else 0
            number = request.form.get('add_number')
            email = request.form.get('add_email')
            departments = Department.query.all()
            for department in departments:
                if request.form.get('add_department') == department.name:
                    department_id = department.id
            jobs = Job.query.all()
            for job in jobs:
                if request.form.get('add_job') == job.name:
                    job_id = job.id
            overtime = request.form.get('add_overtime')
            try:
                user = User(name=name,
                            gender=gender,
                            number=number,
                            department_id=department_id,
                            job_id=job_id,
                            overtime=overtime)
                db.session.add(user)
                db.session.commit()
                return redirect('/admin_staff/')
            except Exception as e:
                print('error:',e)
                return redirect('/admin_staff/')
    return render_template('admin/admin_staff.html')

# @blue.route('/admin_wages/',methods=['GET','POST'])
# @admin_login_required
# def admin_wages():
#     if request.method == 'GET':
#         admin = request.admin
#         return render_template('admin/admin_wages.html',admin=admin.admin)
#     return render_template('admin/admin_wages.html')

@blue.route('/admin/logout/')
def admin_logout():
    response = redirect('/admin/')
    response.delete_cookie('admin_id')
    return response